# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import *
import d_server
from DBOperator import *
from ComFun import *
import time
import d_task

class Friend:
    def __init__(self):
        pass

    def checkFriendInfoList(self, curTime, isForce=False):
        #检测玩家好友信息列表是否更新
        isUpdate = False
        if isForce:
            isUpdate = True
        else:
            if curTime - self.updateFriendInfoTime >= d_server.UpdateFriendInfoListSpace:
                self.updateFriendInfoTime = curTime
                if len(self.friendIdList) != len(self.friendInfoList):
                    isUpdate = True
                else:
                    for friendInfo in self.friendInfoList:
                        id = friendInfo["dbid"]
                        if id in KBEngine.baseAppData:
                            baseData = KBEngine.baseAppData[id]
                            if (baseData["nickName"] != friendInfo["nickName"] or
                                baseData["avatarUrl"] != friendInfo["avatarUrl"] or
                                baseData["score"] != friendInfo["score"] or
                                baseData["weekScore"] != friendInfo["weekScore"] or
                                baseData["lastGetScoreTime"] != friendInfo["lastGetScoreTime"] or
                                (not isSameWeek(curTime, friendInfo["lastGetScoreTime"]) and 0 != friendInfo["weekScore"])):
                                isUpdate = True
                                break
        if isUpdate:
            self.friendInfoList.clear()
            needSelectList = []     #需要从数据库中加载数据的好友id列表
            for id in self.friendIdList:
                if id in KBEngine.baseAppData:
                    baseData = KBEngine.baseAppData[id]
                    friendInfo = {
                        "dbid": id,
                        "nickName": baseData["nickName"],
                        "avatarUrl": baseData["avatarUrl"],
                        "score": baseData["score"],
                        "weekScore": baseData["weekScore"],
                        "lastGetScoreTime": baseData["lastGetScoreTime"],
                    }
                    if not isSameWeek(curTime, friendInfo["lastGetScoreTime"]):
                        friendInfo["weekScore"] = 0
                        friendInfo["lastGetScoreTime"] = curTime
                    self.friendInfoList.append(friendInfo)
                else:
                    needSelectList.append(id)
            self.friendInfoList = self.friendInfoList
            if len(needSelectList) > 0:
                #从数据库中查询好友信息
                SelectFriendList(needSelectList, self.onSlectFriendList)

    def onSlectFriendList(self, result, *args):
        #查询数据库返回玩家好友信息列表
        curTime = int(time.time())
        if result:
            for v in result:
                id = int(v[0].decode('utf8'))
                nickName = v[1].decode('utf8')
                avatarUrl = v[2].decode('utf8')
                score = int(v[3].decode('utf8'))
                weekScore = int(v[4].decode('utf8'))
                lastGetScoreTime = int(v[5].decode('utf8'))
                if not isSameWeek(curTime, lastGetScoreTime):
                    weekScore = 0
                friendInfo = {
                    "dbid": id,
                    "nickName": nickName,
                    "avatarUrl": avatarUrl,
                    "score": score,
                    "weekScore": weekScore,
                    "lastGetScoreTime": lastGetScoreTime,
                }
                self.friendInfoList.append(friendInfo)
                KBEngine.baseAppData[id] = friendInfo
            self.friendInfoList = self.friendInfoList

    def isFriend(self, dbid):
        #检测指定dbid是否是好友
        if dbid in self.friendIdList:
            return True
        return False

    def enterFriendFarm(self, dbid):
        #客户端请求进入好友农场
        if self.isFriend(dbid):
            self.getOtherAccount(dbid, d_server.GetAccountType.Enter, {})
        else:
            self.promptClient("NotFriend")
            return 1

    def enterFriendFarmCallback(self, params):
        self.task_daily_update(d_task.task["mode_friend"]["value"])
        #获取好友数据成功，通知客户端进入好友农场
        self.client.onEenterFriendFarm(params["dbid"], params["fieldNum"], params["fieldList"],
            params["weatherId"], params["shieldIsOpen"], params["shieldEndTime"])

    def steal(self, dbid, index):
        #客户端请求偷菜
        if self.isFriend(dbid):
            params = {"index": index}
            self.getOtherAccount(dbid, d_server.GetAccountType.Steal, params)
        else:
            self.promptClient("NotFriend")
            return 1

    def stealSuccess(self, index, stealScore):
        #偷取成功
        self.client.stealSuccess(index, stealScore)

    def help(self, dbid, index):
        #客户端请求帮好友清除灾害
        if self.isFriend(dbid):
            params = {"index": index}
            self.getOtherAccount(dbid, d_server.GetAccountType.Help, params)
        else:
            self.promptClient("NotFriend")
            return 1

    def watchedUpdateFieldNum(self, dbid, fieldNum):
        #更新好友天气
        self.client.watchedUpdateFieldNum(dbid, fieldNum)

    def watchedUpdateFieldList(self, dbid, fieldList):
        #更新好友天气
        self.client.watchedUpdateFieldList(dbid, fieldList)

    def watchedUpdateWeather(self, dbid, weatherId):
        #更新好友天气
        self.client.watchedUpdateWeather(dbid, weatherId)

    def watchedPlant(self, dbid, index, cropId):
        #好友种植
        self.client.watchedPlant(dbid, index, cropId)

    def watchedHarvest(self, dbid, index):
        #好友收获
        self.client.watchedHarvest(dbid, index)

    def watchedAddDisaster(self, dbid, weatherId, fieldIndexArray):
        #好友添加灾害
        self.client.watchedAddDisaster(dbid, weatherId, fieldIndexArray)

    def watchedClearAllDisaster(self, dbid):
        #好友添加灾害
        self.client.watchedClearAllDisaster(dbid)

    def watchedClearDisaster(self, dbid, index):
        #好友收获
        self.client.watchedClearDisaster(dbid, index)

    def watchedOpenShield(self, dbid):
        #好友激活护盾
        self.client.watchedOpenShield(dbid)

    def watchedAddShieldTime(self, dbid, shieldEndTime):
        #好友激活护盾
        self.client.watchedAddShieldTime(dbid, shieldEndTime)

    # 添加好友
    def friend_binding(self, dbid):
        if not self.isFriend(dbid):
            self.friendIdList.append(dbid)
            self.getOtherAccount(dbid, d_server.GetAccountType.FriendBinding, {} )
            self.checkFriendInfoList(int(time.time()), True)

    def friend_binding_call(self, dbid):
        if not self.isFriend(dbid):
            self.friendIdList.append(dbid)
            self.checkFriendInfoList(int(time.time()), True)